<?php
	// Where the file is going to be placed 
//	$subdir = date("Y-m");
//	$file_path = $_SERVER["DOCUMENT_ROOT"] . "/dropped_files/" . $subdir;
//	mkdir($file_path, 0777);
//	chmod($file_path, 0777);
	
	$file_path = $_SERVER["DOCUMENT_ROOT"] . "/dropped_files/";
	
	/* Add the original filename to our target path. Result is "uploads/filename.extension" */
	$target_path = $file_path . "/" . basename($_FILES['uploadedfile']['name']);
	
	$forbiddenMimes = array('application/octet-stream'); // EXE not allowed

    if( in_array($_FILES['uploadedfile']['type'], $forbiddenMimes) == false ) {
    	
    	$filename = basename($_FILES['uploadedfile']['name']);
    	
    	// Rename file if it already exists.
    	$i = 0;
    	while( file_exists($target_path) ) {
    		$i++;
			$file_parts = explode(".", basename( $_FILES['uploadedfile']['name']));
			$array_size = sizeof($file_parts);
			
			$tmp_filename = $file_parts[($array_size-2)] . "-" . $i;
			$file_parts[($array_size-2)] = $tmp_filename;
			
			$new_filename = implode(".", $file_parts);
			$target_path = $file_path . "/" . $new_filename;
			
			$filename = $new_filename;
		}
		
		$_FILES['uploadedfile']['name'] = $filename;
    	
		if(@move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
			
			$browser_info = @get_browser(null, true);
			$ip = $_SERVER["REMOTE_ADDR"];
			$file_name = addslashes(basename( $_FILES['uploadedfile']['name']));
			$file_size = $_FILES['uploadedfile']['size'];
			$file_type = addslashes($_FILES['uploadedfile']['type']);
			$platform = $browser_info["platform"];
			$browser = $browser_info["parent"];
			
			// DATABASE ENTRY
			unset ($db);  
			
			if (!($db = mysql_connect("localhost", "web45", "ocarina."))) { 	
				// die("Cannot connect to database"); 
			} if (!mysql_select_db("usr_web45_3", $db)) { 	
				// die("Cannot connect to database"); 
			}  
			
			$insert = "INSERT INTO dropped_files (ip, file_name, file_size, file_type, subdir, platform, browser) " .
				"VALUES ('$ip', '$file_name', '$file_size', '$file_type', '$subdir', '$platform', '$browser') ";
			$insertnow = mysql_query($insert, $db);
			
	    	echo "The file " .  basename( $_FILES['uploadedfile']['name']) . " has been uploaded.";
		} else {
	    	echo "There was an error uploading the file, please try again!";
		}
	} else {
		echo "Forbidden file type.";
	}
?>